package com.kaizzi.data.ppt.template;

import com.fasterxml.jackson.databind.JsonNode;
import com.kaizzi.data.common.been.TempBeen;
import com.kaizzi.data.common.utils.DateUtil;
import com.kaizzi.data.common.utils.StringUtil;
import com.kaizzi.data.jdl.service.LogService;
import com.kaizzi.data.ppt.TemplateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.sl.usermodel.StrokeStyle;
import org.apache.poi.sl.usermodel.TableCell;
import org.apache.poi.sl.usermodel.TextParagraph;
import org.apache.poi.sl.usermodel.VerticalAlignment;
import org.apache.poi.xslf.usermodel.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * @author Kzen
 * @Description description
 * @date 2020/9/27
 */
@Slf4j
@Component
public class Template10 {

    @Resource
    private TemplateUtil templateUtil;
    @Resource
    private LogService logService;

    private static final String total = "总计";

    //特殊处理，重新绘制表格
    public void table(XSLFShape shape, JsonNode data, XSLFSlide slide) {

//        int a = 1/0;

        Color color = new Color(232, 204, 186);
        Color color1 = new Color(192, 0, 0);
        Color color2 = new Color(0, 176, 80);
        slide.removeShape(shape);

        XSLFTable table = slide.createTable();
        table.setAnchor(new Rectangle2D.Double(40, 95, 0, 0));
        //日期排序
        List<String> dateList = DateUtil.getDateMonth();
        dateList.sort(Comparator.comparing(String::trim));
        List<TempBeen> beens = getDataList(data);
        // 具体行数
        for (int row = 0; row < getWesShops().size()+2; row++) {
            XSLFTableRow tableRow = table.addRow();
            //lie
            for (int col = 0; col < dateList.size()+2; col++) {
                //
                XSLFTableCell cell = tableRow.addCell();
                cell.setBorderCap(TableCell.BorderEdge.bottom, StrokeStyle.LineCap.ROUND);
                cell.setBorderColor(TableCell.BorderEdge.bottom,Color.BLACK);
                cell.setBorderColor(TableCell.BorderEdge.left,Color.BLACK);
                cell.setBorderColor(TableCell.BorderEdge.right,Color.BLACK);
                cell.setBorderColor(TableCell.BorderEdge.top,Color.BLACK);
                cell.setVerticalAlignment(VerticalAlignment.MIDDLE);
                XSLFTextParagraph paragraph = cell.addNewTextParagraph();
                paragraph.setTextAlign(TextParagraph.TextAlign.CENTER);
                XSLFTextRun textRun = paragraph.addNewTextRun();
                tableRow.setHeight(30d);
                textRun.setFontFamily("微软雅黑");
                table.setColumnWidth(col,(double) 750/(dateList.size()+1));
                textRun.setFontSize(10d);

                if (col ==0){
                    table.setColumnWidth(col,140);
                }
                if (row==0){
                    cell.setFillColor(color1);
                }
                if (row>0 && row<4){
                    cell.setFillColor(color);
                }
                if (row ==0){
                    textRun.setFontColor(Color.WHITE);
                    textRun.setFontSize(12d);
                    if (dateList.size()>7){
                        textRun.setFontSize(10.5d);
                    }
                    textRun.setBold(true);
                    if (col == 0){
                        textRun.setText("门店");
                        continue;
                    }
                    if (col == dateList.size()+1){
                        textRun.setText(total);
                        continue;
                    }
                    textRun.setText(dateList.get(col-1));
                    continue;
                }

                if (row == getWesShops().size()+1){
                    textRun.setFontSize(12d);
                    textRun.setBold(true);
                    if (col ==0){
                        textRun.setText(total);
                        continue;
                    }
                    if (col == dateList.size()+1){
                        textRun.setFontColor(Color.WHITE);
                        cell.setFillColor(color2);
                    }
                }
                if (col == dateList.size()){
                    //获取最后一月排序最高两个数字
                    List<TempBeen> lastTopData = getlastMonth(beens);
                    lastTopData.sort(Comparator.comparing(TempBeen::getTempCount).reversed());
                    String s = StringUtil.join(lastTopData.get(0).getTempCount());
                    String s1 = StringUtil.join(lastTopData.get(1).getTempCount());
                    String aa = getCellData(row,col,beens,dateList);
                    if (aa.equals(s) || aa.equals(s1)){
                        textRun.setBold(true);
                        textRun.setFontColor(color1);
                    }else {
                        textRun.setBold(false);
                        textRun.setFontColor(Color.BLACK);
                    }
                }
                textRun.setText(getCellData(row,col,beens,dateList));
            }
        }
    }

    private List<TempBeen> getlastMonth(List<TempBeen> data) {
        Map<String, List<TempBeen>> collect = data.stream().collect(Collectors.groupingBy(TempBeen::getTempData));
        return collect.get(total);
    }

    private List<TempBeen> getRowData(int row, List<TempBeen> beens) {
        if (row == 0){
            return beens;
        }
        Map<String, List<TempBeen>> collect = beens.stream().collect(Collectors.groupingBy(TempBeen::getTempData));
        Map<String, List<TempBeen>> collect1 = beens.stream().collect(Collectors.groupingBy(TempBeen::getTempName));
        List<TempBeen> beens1 = collect.get(total);
        List<TempBeen> temp = beens1.stream().filter(been -> !been.getTempName().equals(total)).collect(toList());
        List<TempBeen> temp1 = beens1.stream().filter(been -> been.getTempName().equals(total)).collect(toList());
        temp.sort(Comparator.comparing(TempBeen::getTempCount).reversed());
        temp.addAll(temp1);
        return collect1.get(temp.get(row - 1).getTempName());
    }

    private List<TempBeen> getDataList(JsonNode data) {
        List<TempBeen> dataList = new ArrayList<>();
        for (JsonNode node : data.get("wesList")) {
            TempBeen tempBeen = new TempBeen();
            tempBeen.setTempData(node.get("tempData").asText());
            tempBeen.setTempName(node.get("tempName").asText());
            tempBeen.setTempCount(node.get("tempCount").asLong());
            dataList.add(tempBeen);
        }
        return dataList;
    }

    private String getCellData(int row,int col,List<TempBeen> data,List<String> dateList){

        if (row == 0){
            List<String> dateMonth = DateUtil.getDateMonth();
            dateMonth.sort(Comparator.comparing(String::trim).reversed());
            return transStr(dateMonth.get(col - 1));
        }
        String rowName = getRowName(row,data);
        if (col == 0){
            return rowName;
        }
        String colName = getColName(col,dateList);
        List<TempBeen> collect = data.stream().filter(been -> been.getTempName().equals(rowName) && been.getTempData().equals(colName)).collect(toList());
        if (collect.size() < 1){
            return StringUtil.decimalFormat2(0);
        }
        return StringUtil.decimalFormat2(collect.get(0).getTempCount());
    }

    private String getColName(int col, List<String> dateList) {
        if (col == dateList.size()+1){
            return total;
        }
        return transStr(dateList.get(col-1));
    }

    private String getRowName(int row,List<TempBeen> beens) {
        return getRowData(row, beens).get(0).getTempName();
    }

    private String transStr(String string){
        return string.replace("/","年")+"月";
    }

    private List<String> getWesShops(){
        return Arrays.asList("中山公园店、大华朗香店","虹桥南丰城店、日月光店","古北店、长寿店","番禺店、宝华紫薇","世纪公园店、滨江苑",
                "古北1699店、合生汇店","嘉园店、长江国际店","新天地店、上滨广场","卢湾店、文峰广场店","汇景天地店、百联世纪店");
    }

    //文字替换
    public void text(List<XSLFTextParagraph> textParagraphs, JsonNode data) {
        if(textParagraphs==null||textParagraphs.size()==0){
            return;
        }
        for (XSLFTextParagraph textParagraph : textParagraphs) {
            if(textParagraph==null){
                continue;
            }
            List<XSLFTextRun> textRuns = textParagraph.getTextRuns();
            if(textRuns==null){
                continue;
            }
            for (XSLFTextRun textRun : textRuns) {
                if (textRun == null || textRun.getXmlObject()  == null){
                    return;
                }
                try {
                    if (textRun.getRawText().equals("10KEY-2")){
                        String title = data.get("title").asText();
                        templateUtil.text(textParagraph,title,false);
                        break;
                    }
                    if (textRun.getRawText().equals("10KEY-1")){
                        String dataPeriod = data.get("dataPeriod").asText();
                        textRun.setText(dataPeriod);
                        break;
                    }
                }catch (Exception e){
                    logService.setDataLogStatus("ppt-error");
                    log.error("page:{},text异常原因:{}",10,e);
                }
            }
        }
    }
}
